package server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;

import model.Line;
import model.Move;
import model.Oval;
import model.Rectangle;
import model.SelectBox;
import model.ServerShape;
import model.Smily;
import socket.BaseClient;
import socket.Server;


public class WhiteboardServer extends Server{
	
	private static WhiteboardServer instance;
	
	Vector<ServerShape> shapes = new Vector<ServerShape>();
	
	protected void addShape(String args) {
		ServerShape c = null;
		if (args.contains("Smily"))
			c = new Smily();
		else if (args.contains("Line"))
			c = new Line();
		else if (args.contains("Oval"))
			c = new Oval();
		else if (args.contains("Rectangle"))
			c = new Rectangle();
		else if (args.contains("SelectBox"))
			c = new SelectBox();
		else if (args.contains("Move"))
			c = new Move();
		if (c != null) {
			c.parse(args);
			shapes.add(c);
			log("create shape " + args, true);
		}
	}
	
	@Override
	protected void parseCommand(String mesg){
		if (mesg.contains("p_create_shape")) {
			// UOTUV p_sendp_create_shape 39;127;256;329;39;256;notsel;Linep_eom
			String args = mesg.substring(
					mesg.indexOf(D_CREATE_SHAPE) + D_CREATE_SHAPE.length(),
					mesg.indexOf(EOM)).trim();
			addShape(args);
		}	
	}
	
	protected void broadcastShapes() throws IOException{
		for (ServerShape shape : shapes) {
			String mesg="SERVER "+SEND+D_CREATE_SHAPE+" "+shape.asString()+EOM;
			synchronized (clients) {
				for (Iterator<BaseClient> i = clients.iterator(); i.hasNext();)
					new PrintWriter(((i.next()).getSocket()).getOutputStream(),
							true).println(mesg);
			}
		}	
	}
	
	
	protected void sendShapes(BaseClient client) throws IOException{
		for (ServerShape shape : shapes) {
			String mesg="SERVER "+SEND+D_CREATE_SHAPE+" "+shape.asString()+EOM;
		    new PrintWriter(((client).getSocket()).getOutputStream(),
							true).println(mesg);
		}	
	}
	
	public void addClient(Socket sock, BaseClient client) throws IOException {
		super.addClient(sock, client);
		sendShapes(client);
	}
	
	public static WhiteboardServer getInstance() {
		if (null == instance) {
			instance = new WhiteboardServer();
		}
		return instance;
	}	
	
	public static void main(String[] args) throws Exception {
		WhiteboardServer monServeur = WhiteboardServer.getInstance();
		monServeur.run();
	}

}
